<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 管理系统
 */
class Custom extends CI_Controller
{
  private $data;
  function __construct()
  {
    parent::__construct();
    $params = array('app' => 'custom');
    $this->load->library('Use_smarty', $params, 'smarty');
    $this->load->model("Custom_model");
    $this->load->helper(array('form', 'url'));//上传

    // 服务器
    // $config = array('appID' => '99ad9f932ca240be',
    //                'appSecret' => 'c9050eedadfc7b6b6d6ce8095087c67f',
    //                 'callback' => 'http://f.yiban.cn/iapp132049');
    //
    //  $this->load->library('YibanSDK', $config, 'yiban');
    //  if (!$this->input->get('verify_request')) {
    //      $this->session->url = $_SERVER['REQUEST_URI'];
    //  }
    //  //var_dump($this->session);
    //  if (!isset($this->session->token)) {     // 未获取授权
    //  /**
    //   * 从授权服务器回调返回时，URL中带有code（授权码）参数.
    //   */
    //      $au = $this->yiban->getAuthorize();
    //      if ($this->input->get('verify_request')) {
    //          /**
    //           * 使用授权码（code）获取访问令牌
    //           * 若获取成功，返回 $info['access_token']
    //           * 否则查看对应的 msgCN 查看错误信息.
    //           */
    //          $info = $this->yiban->getFrameUtil()->perform();
    //          //var_dump($info);
    //          if (!isset($info['visit_oauth']['access_token'])) {
    //              //echo $info['msgCN'];
    //              redirect($au->forwardurl());
    //          }
    //          $this->session->token = $info['visit_oauth']['access_token'];
    //          $this->data['user_info']['yb_userid'] = $info['visit_user']['userid'];
    //          $this->data['user_info']['yb_username'] = $info['visit_user']['username'];
    //          header('Location: '.$this->session->url);
    //      } else {   // 重定向到授权服务器（原sdk使用header()重定向）
    //          redirect($au->forwardurl());
    //          // header('Location: ' . $au->forwardurl());
    //      }
    //  }
    //  if (!isset($this->data['user_info']['yb_userhead']) && $this->session->token) {
    //      $this->user = $this->yiban->getUser($this->session->token);
    //      $this->data['user_info'] = $this->user->me()['info'];
    //  }
    //  $this->user = $this->yiban->getUser($this->session->token);
    //  $this->data['user_info'] = $this->user->me()['info'];
    $this->data['user_info']['yb_userid'] = 7041045;

    $check = $this->Custom_model->AdminCheck($this->data['user_info']['yb_userid']);
    if(!$check)
    {
        echo "请联系管理员检查权限";
        exit;
    }
    else if($this->Custom_model->SuperYBCheck($this->data['user_info']['yb_userid']))
    {
        $this->data['EditCommunity'] ='';                        //YB超级管理员拥有操作社团的权利
    }
    else if($this->Custom_model->SuperCheck($this->data['user_info']['yb_userid']))
    {
        $this->data['EditAdmin'] ='';                        //超级管理员拥有操作管理员的权利
    }
    $this->data['Community'] = $check['belongto'];
  }

  public function index($value='')
  {
    $this->data['home'] = $this->Custom_model->HomeData($this->data['Community']);
    $this->smarty->tplview('index',$this->data);
  }
  /**
   * 操作管理员
   */
  public function Opt($value='')
  {
    $this->data['C_lists'] = $this->Custom_model->CommunityList();
    $this->data['lists'] = $this->Custom_model->AdminList($this->data['Community']);
    $this->smarty->tplview('opt',$this->data);
  }

  public function DeleteA($yb_userid='')
  {
    $this->Custom_model->DeleteAdmin($yb_userid);
    echo '<script>alert("删除成功");history.go(-1);</script>';
  }

  public function AddAdmin($value='')
  {
    $PostData = $this->input->post();

    if(! isset($this->data['EditCommunity']))
    {
      $PostData['belongto'] = $this->data['Community'];
    }
    $this->Custom_model->AddAdmin($PostData);
    echo '<script>alert("添加成功");history.go(-1);</script>';
  }

  public function List($value='')
  {
    $this->data['lists'] = $this->Custom_model->AllList($this->data['Community']);
    $this->smarty->tplview('list',$this->data);
  }

  public function EditCommunity($value='')
  {

    $this->data['lists'] = $this->Custom_model->CommunityList();

    $config['upload_path']      = './uploads/Custom';
    $config['allowed_types']    = 'pdf|jpg|png';
    $config['max_size']         = 2048;
    $config['max_width']        = 1024;
    $config['max_height']       = 768;
    $config['encrypt_name']     = true;

    $this->load->library('upload', $config);

    $sign['sign'] = "ok";          //是否有未上传的文件
    if ( ! $this->upload->do_upload('pdf') )
    {
        $data['error']   = $this->upload->display_errors()."<br>请确认社团介绍文件是否正常";
        $sign['sign']    = "wrong";
        $sign['content'] = "请确认社团介绍文件是否正常";
    }
    else
    {
        $data['upload_data']['pdf'] = $this->upload->data();
    }

    if( ! $this->upload->do_upload('logo') )        //大小
    {
        $data['error'] = $this->upload->display_errors()."<br>请确认logo";
        $sign['sign']    = "wrong";
        $sign['content'] = "请确认logo";
    }
    else
    {
        $data['upload_data']['logo'] = $this->upload->data();
    }
    if( ! $this->upload->do_upload('phpto1') )
    {
        $data['error'] = $this->upload->display_errors()."<br>请确认第一张介绍图片";
        $sign['sign']    = "wrong";
        $sign['content'] = "请确认第一张介绍图片";
    }
    else
    {
        $data['upload_data']['photo1'] = $this->upload->data();
    }
    if( ! $this->upload->do_upload('phpto2') )
    {
        $data['error'] = $this->upload->display_errors()."<br>请确认第二张介绍图片";
        $sign['sign']    = "wrong";
        $sign['content'] = "请确认第二张介绍图片";
    }
    else
    {
        $data['upload_data']['photo2'] = $this->upload->data();
    }
    if( ! $this->upload->do_upload('phpto3') )
    {
        $data['error'] = $this->upload->display_errors()."<br>请确认第三张介绍图片";
        $sign['sign']    = "wrong";
        $sign['content'] = "请确认第三张介绍图片";
    }
    else
    {
        $data['upload_data']['photo3'] = $this->upload->data();
    }


    if($sign['sign']  == "wrong")
    {
      if(isset($data['error']))
      {
        if(stripos($data['error'],'You did not select a file to upload.'))
        {
          $this->data['error'] = '请选择要上传的文件'.'<br>'.$sign['content'];
        }
      }
      $this->smarty->tplview('EditCommunity',$this->data);
    }
    else
    {
      $post = $this->input->post();
      $post1['description_temp'] = base_url().'uploads/Custom/'.$data['upload_data']['pdf']['file_name'];
      $page = $this->getPageTotal($post1['description_temp']);
      $nima = $data['upload_data']['pdf']['file_path'].$data['upload_data']['pdf']['file_name'];
      $tema = $data['upload_data']['pdf']['file_path'].$data['upload_data']['pdf']['raw_name'].".jpg";
      exec("convert $nima $tema");
      $post['description'] = "";
      if($page > 1)
      {
        for ($i=$page-1; $i >= 0; $i--) {
          if($i == 0)
          {
            $post['description'].=base_url().'uploads/Custom/'.$data['upload_data']['pdf']['raw_name'].'-'.$i.".jpg";
          }
          else {
            $post['description'].=base_url().'uploads/Custom/'.$data['upload_data']['pdf']['raw_name'].'-'.$i.".jpg"."##";
          }
        }
      }
      else {
        $post['description'].=base_url().'uploads/Custom/'.$data['upload_data']['pdf']['raw_name'].".jpg";
      }
      // var_dump($page);exit;
      // var_dump($post['description']);
      $post['logo']   = base_url().'uploads/Custom/'.$data['upload_data']['logo']['file_name'];
      $post['image1'] = base_url().'uploads/Custom/'.$data['upload_data']['photo1']['file_name'];
      $post['image2'] = base_url().'uploads/Custom/'.$data['upload_data']['photo2']['file_name'];
      $post['image3'] = base_url().'uploads/Custom/'.$data['upload_data']['photo3']['file_name'];
      $this->Custom_model->AddCommunity($post);
      echo "<script>alert('添加成功');history.go(-1);</script>";
    }


  }

  /**
   * 设置社团的部门和组之间的结构
   * @note 查看是否已经被设置
   */
  public function Set($value='')
  {
    $param = $this->input->post();

    var_dump($param);
    $bumen    = explode("##",$param['bumen']);
    $num      =  count($bumen);
    $zu1['zu'] = explode("##",$param['zu']);
    for ($i=0; $i < $num; $i++) {
      $zu[$i] = explode("**",$zu1['zu'][$i]);
    }
    $this->Custom_model->Set($param['shetuan'],$bumen,$zu);
    echo '<script>alert("设置完成");history.go(-1);</script>';
  }

  public function AddCommunity($value='')
  {
    $this->Custom_model->AddCommunity($this->input->post());
    echo '<script>alert("添加成功");history.go(-1);</script>';
  }

  public function DelateC($name1='')
  {
    $this->Custom_model->DeleteCommunity($name1);
    echo '<script>alert("删除成功");history.go(-1);</script>';
  }

  /**
  * 获取PDF的页数
  */
  public function getPageTotal($path=""){
      // 打开文件
      if (!$fp = @fopen($path,"r")) {
      // if (!$fp = @fopen("http://127.0.0.1/recuit/pdf/delete.pdf","r")) {
        $error = "打开文件{$path}失败";
        return false;
      }
      else {
        $max=0;
        while(!feof($fp)) {
          $line = fgets($fp,255);
          if (preg_match('/\/Count [0-9]+/', $line, $matches)){
            preg_match('/[0-9]+/',$matches[0], $matches2);
            if ($max<$matches2[0]) $max=$matches2[0];
          }
        }
        fclose($fp);
        // 返回页数
        return $max;
      }
  }

  public function Export()
  {
    $this->load->library('DataOption');
    $contents = $this->Custom_model->AllList($this->data['Community']);
    $base = 'A';$array_num=0;$data = ($this->Custom_model->ExportDataList("record"));
    foreach ($data as $key => $value) {
      $temp[$array_num++] = $base++.'1';
    }
    $subtitle = array_combine(array_values($temp),array_values($data));
    // var_dump($subtitle);exit;
    {
      $this->dataoption->Export("中南大学".$this->data['Community']."招新统计",
                              $subtitle,
                              $contents,
                              $this->data['Community']."招新统计.xls",
                            4);
    }
  }

}
